using EFCoreDemo.Models;
using EFCoreDemo.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace EFCoreDemo.Controllers;

[ApiController]
[Route("[controller]")]
public class DemoController {
    private DemoContext _demoContext;

    public DemoController(DemoContext demoContext) {
        _demoContext = demoContext;
    }

    [Route("post")]
    [HttpPost]
    public async Task<ActionResult<DemoModel>>
        Post([FromBody] DemoModel model) {
        var modelEntry = await _demoContext.AddAsync(model);
        await _demoContext.SaveChangesAsync();
        return modelEntry.Entity;
    }

    [Route("put")]
    [HttpPut]
    public async Task<ActionResult<DemoModel>> Put([FromBody] DemoModel model) {
        var modelToUpdate =
            await _demoContext.DemoModels.FirstOrDefaultAsync(p =>
                p.Id == model.Id);
        modelToUpdate.Name = model.Name;
        await _demoContext.SaveChangesAsync();
        return modelToUpdate;
    }

    [Route("delete")]
    [HttpDelete]
    public async Task<ActionResult<DemoModel>> Delete(int id) {
        var modelToDelete =
            await _demoContext.DemoModels.FirstOrDefaultAsync(p => p.Id == id);
        _demoContext.Remove(modelToDelete);
        await _demoContext.SaveChangesAsync();
        return modelToDelete;
    }

    [Route("list")]
    [HttpGet]
    public async Task<ActionResult<IEnumerable<DemoModel>>> List() {
        return await _demoContext.DemoModels.ToListAsync();
    }
}